package myschool.web;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author oldliu
 * @since 1.0
 */
public class HelloServlet extends HttpServlet {
    public HelloServlet(){
        System.out.println("HelloServlet 被创建了");
    }

    @Override
    public void init() throws ServletException {
        System.out.println("HelloServlet初始化了");

    }

    @Override
    public void destroy() {
        System.out.println("HelloServlet销毁了");
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("请求方式："+req.getMethod());
        super.service(req, resp);
        System.out.println("请求结束！");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理get请求
        //>>>req.setCharacterEncoding("");
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        writer.write("<html>");
        writer.write("<body>");
        writer.write("<h1>");
        writer.write("这是一个get请求！");
        writer.write("ip:"+req.getRemoteHost());
        writer.write("</h1>");
        writer.write("<h1>");
        writer.write(req.getServletContext().getRealPath(""));
        writer.write("</h1>");
        writer.write("</body>");
        writer.write("</html>");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理post请求
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        writer.write("<html>");
        writer.write("<body>");
        writer.write("<h1>");
        writer.write("这是一个post请求！");
        writer.write("ip:"+req.getRemoteHost());
        writer.write("</h1>");
        writer.write("</body>");
        writer.write("</html>");
    }
}
